const JWT = require('jsonwebtoken')

module.exports = options => {
  return async function (ctx, next) {
    let token = ctx.request.header.authorization || ''
    token = token.replace('Bearer ', '')
    // console.log('token==============', token)
    const method = ctx.method.toLowerCase()
    if (method === 'get') {
      await next()
    } else if (!token) {
      if (
        ctx.path === '/api/v1/signup' ||
        ctx.path === '/api/v1/signin' ||
        ctx.path === '/api/v1/signin/wxchat'
      ) {
        await next()
      } else {
        ctx.throw(401, '未登录, 请先登录!!!')
      }
    } else {
      let decode
      try {
        decode = await JWT.verify(token, options.secret)
        if (!decode || !decode.userId) {
          ctx.throw(401, '没有权限，请登录')
        }
        if (Date.now() - decode.expire > 0) {
          ctx.throw(401, 'Token已过期')
        }
        const user = await ctx.model.User.find({
          openid: decode.openid
        })
        if (user) {
          ctx.state.user = ctx.state.user || {}
          ctx.state.user.id = decode && decode.userId
          console.log('ctx.state.user===========', ctx.state.user)
          await next()
        } else {
          ctx.throw('401', '用户信息验证失败')
        }
      } catch (e) {
        // console.log('token error=========', e)
        ctx.throw('401', e.message)
      }
    }
  }
}
